package com.valkyries.jhhj.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.valkyries.jhhj.common.Result;
import com.valkyries.jhhj.constant.CacheConstants;
import com.valkyries.jhhj.domain.User;
import com.valkyries.jhhj.domain.model.LoginBody;
import com.valkyries.jhhj.exception.*;
import com.valkyries.jhhj.service.LoginService;
import com.valkyries.jhhj.service.UserService;
import com.valkyries.jhhj.utils.RedisCache;
import com.valkyries.jhhj.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisCache redisCache;

    @Override
    public Result login(LoginBody loginBody) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(loginBody.getUuid(), "");
        String captcha = redisCache.getCacheObject(verifyKey);
//        System.out.println("redis中的验证码:" + captcha);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            throw new CaptchaTimeOutException();
        }
        if (!captcha.equals(loginBody.getCode())) {
            throw new CaptchaErrorException();
        }
        if(loginBody.getPassword().length() > 32 || loginBody.getPassword().length() < 6){
            throw new TextLengthException(6 , 32 , "密码");
        }
        User user = userService.queryUserByUsername(loginBody.getUsername());
        if (user != null) {
            if (Objects.equals(user.getPassword(), loginBody.getPassword())) {
                StpUtil.login(user.getUserId());
                return Result.ok("登录成功").setData(user);
            } else {
                throw new PasswordErrorException();
            }
        }
        throw new UserNameNotExistException();
    }
}
